package shu;

public class _03BigHeapSort {
    public static void main(String[] args) {
        int[] a = {33,12,7,66,4,89,5};
        sort(a);
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
    }

    public static void sort(int[] a){
        int n = a.length;
        bigHeap(a);
        for (int x = n-1;x >= 0; x--){
            swap(a,0,x);
            BigHeapFixDown(a,0,x);
        }

    }

    public static void bigHeap(int[] a ){
        int n = a.length;
        for (int i = n/2-1;i >=0 ; i--){
            BigHeapFixDown(a,i,n);
        }
    }

    public static void BigHeapFixDown(int[] a,int i ,int n){
        int left = 2*i+1;
        int right = 2*i+2;
        if (left >=n){
            return;
        }
        int max = left;
        if (right>=n){
            max = left;
        }else {
            if (a[right] > a[left]){
                max = right;
            }
        }
        if (a[i] >= a[max]){
            return;
        }
        swap(a,i,max);
        BigHeapFixDown(a,max,n);

    }

    public static void swap(int[] a,int i ,int j ){
        int temp = a[i];
        a[i] = a[j];
        a[j] =temp;
    }
}
